<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import {
  Button,
  Card,
  Col,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

import { getBusinessResources } from '#/api/resource-center';

const loading = ref(false);
const resourceList = ref<any[]>([]);
const total = ref(0);

const searchForm = reactive({
  keyword: '',
  businessType: '',
  status: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const columns = [
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '资源编码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '业务类型',
    dataIndex: 'businessType',
    key: 'businessType',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '位置',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '容量',
    dataIndex: 'capacity',
    key: 'capacity',
    width: 80,
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 表单相关
const formVisible = ref(false);
const formTitle = ref('新增业务资源');
const formRef = ref();
const formData = reactive({
  id: '',
  name: '',
  code: '',
  businessType: '',
  status: 'ACTIVE',
  location: '',
  capacity: 1,
  price: 0,
  description: '',
});

const formRules = {
  name: [{ required: true, message: '请输入资源名称' }],
  code: [{ required: true, message: '请输入资源编码' }],
  businessType: [{ required: true, message: '请选择业务类型' }],
  status: [{ required: true, message: '请选择状态' }],
  capacity: [{ required: true, message: '请输入容量' }],
  price: [{ required: true, message: '请输入价格' }],
};

// 详情相关
const detailVisible = ref(false);
const selectedResource = ref<any>({});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      businessType: searchForm.businessType,
      status: searchForm.status,
    };

    const response = await getBusinessResources(params);
    resourceList.value = response.items || [];
    total.value = response.total || 0;
    pagination.total = total.value;
  } catch (error) {
    console.warn('加载业务资源失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    businessType: '',
    status: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 打开表单
const openResourceForm = (type: 'create' | 'edit', record?: any) => {
  formTitle.value = type === 'create' ? '新增业务资源' : '编辑业务资源';
  typetype;
  formVisible.value = true;

  if (type === 'edit' && record) {
    Object.assign(formData, record);
  } else {
    Object.assign(formData, {
      id: '',
      name: '',
      code: '',
      businessType: '',
      status: 'ACTIVE',
      location: '',
      capacity: 1,
      price: 0,
      description: '',
    });
  }
};

// 提交表单
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate();
    // TODO: 调用API保存数据
    message.success(formData.id ? '更新成功' : '创建成功');
    TODOTODO;
    formVisible.value = false;
    loadData();
  } catch (error) {
    console.warn('表单验证失败:', error);
  }
};

// 取消表单
const handleFormCancel = () => {
  formVisible.value = false;
  formRef.value?.resetFields();
};

// 查看详情
const viewResource = (record: any) => {
  selectedResource.value = record;
  detailVisible.value = true;
};

// 删除资源
const deleteResource = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除资源"${record.name}"吗？`,
    onOk: async () => {
      try {
        // TODO: 调用API删除数据
        message.success('删除成功');
        loadData();
      } catch (error) {
        console.warn('删除失败:', error);
        message.error('删除失败');
      }
    },
  });
};

// 工具函数
const getBusinessTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    HOTEL: 'blue',
    APARTMENT: 'green',
    HOT_SPRING: 'orange',
    RESTAURANT: 'purple',
    PET_MEDICAL: 'cyan',
    MEDICAL_BEAUTY: 'pink',
    TRAINING: 'geekblue',
  };
  return colors[type] || 'default';
};

const getBusinessTypeText = (type: string) => {
  const texts: Record<string, string> = {
    HOTEL: '酒店',
    APARTMENT: '公寓',
    HOT_SPRING: '温泉洗浴',
    RESTAURANT: '餐饮',
    PET_MEDICAL: '宠物医疗',
    MEDICAL_BEAUTY: '医美',
    TRAINING: '培训班',
  };
  return texts[type] || type;
};

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    ACTIVE: 'green',
    INACTIVE: 'red',
    DRAFT: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    ACTIVE: '激活',
    INACTIVE: '非激活',
    DRAFT: '草稿',
  };
  return texts[status] || status;
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="business-resource-catalog">
    <div class="catalog-header">
      <Row :gutter="16">
        <Col :span="8">
          <Input
            v-model:value="searchForm.keyword"
            placeholder="搜索业务资源名称、编码"
            allow-clear
            @change="handleSearch"
          />
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.businessType"
            placeholder="业务类型"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="HOTEL">酒店</SelectOption>
            <SelectOption value="APARTMENT">公寓</SelectOption>
            <SelectOption value="HOT_SPRING">温泉洗浴</SelectOption>
            <SelectOption value="RESTAURANT">餐饮</SelectOption>
            <SelectOption value="PET_MEDICAL">宠物医疗</SelectOption>
            <SelectOption value="MEDICAL_BEAUTY">医美</SelectOption>
            <SelectOption value="TRAINING">培训班</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.status"
            placeholder="状态"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="ACTIVE">激活</SelectOption>
            <SelectOption value="INACTIVE">非激活</SelectOption>
            <SelectOption value="DRAFT">草稿</SelectOption>
          </Select>
        </Col>
        <Col :span="8">
          <Space>
            <Button type="primary" @click="handleSearch">搜索</Button>
            <Button @click="handleReset">重置</Button>
            <Button type="primary" @click="openResourceForm('create')">
              新增业务资源
            </Button>
          </Space>
        </Col>
      </Row>
    </div>

    <div class="catalog-content">
      <Card title="业务资源目录" :bordered="false">
        <Table
          :columns="columns"
          :data-source="resourceList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'businessType'">
              <Tag :color="getBusinessTypeColor(record.businessType)">
                {{ getBusinessTypeText(record.businessType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'price'">
              ¥{{ record.price }}
            </template>
            <template v-else-if="column.key === 'action'">
              <Space>
                <Button type="link" size="small" @click="viewResource(record)">
                  查看
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="openResourceForm('edit', record)"
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="deleteResource(record)"
                >
                  删除
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </Card>
    </div>

    <!-- 资源表单弹窗 -->
    <Modal
      v-model:open="formVisible"
      :title="formTitle"
      width="800px"
      @ok="handleFormSubmit"
      @cancel="handleFormCancel"
    >
      <Form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="资源名称" name="name">
              <Input
                v-model:value="formData.name"
                placeholder="请输入资源名称"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="资源编码" name="code">
              <Input
                v-model:value="formData.code"
                placeholder="请输入资源编码"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="业务类型" name="businessType">
              <Select
                v-model:value="formData.businessType"
                placeholder="请选择业务类型"
              >
                <SelectOption value="HOTEL">酒店</SelectOption>
                <SelectOption value="APARTMENT">公寓</SelectOption>
                <SelectOption value="HOT_SPRING">温泉洗浴</SelectOption>
                <SelectOption value="RESTAURANT">餐饮</SelectOption>
                <SelectOption value="PET_MEDICAL">宠物医疗</SelectOption>
                <SelectOption value="MEDICAL_BEAUTY">医美</SelectOption>
                <SelectOption value="TRAINING">培训班</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="状态" name="status">
              <Select v-model:value="formData.status" placeholder="请选择状态">
                <SelectOption value="ACTIVE">激活</SelectOption>
                <SelectOption value="INACTIVE">非激活</SelectOption>
                <SelectOption value="DRAFT">草稿</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="容量" name="capacity">
              <InputNumber
                v-model:value="formData.capacity"
                :min="1"
                style="width: 100%"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="价格" name="price">
              <InputNumber
                v-model:value="formData.price"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="位置" name="location">
          <Input
            v-model:value="formData.location"
            placeholder="请输入资源位置"
          />
        </FormItem>
        <FormItem label="描述" name="description">
          <Input.TextArea
            v-model:value="formData.description"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 资源详情弹窗 -->
    <Modal
      v-model:open="detailVisible"
      title="资源详情"
      width="600px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="资源名称">
          {{ selectedResource.name }}
        </DescriptionsItem>
        <DescriptionsItem label="资源编码">
          {{ selectedResource.code }}
        </DescriptionsItem>
        <DescriptionsItem label="业务类型">
          <Tag :color="getBusinessTypeColor(selectedResource.businessType)">
            {{ getBusinessTypeText(selectedResource.businessType) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="状态">
          <Tag :color="getStatusColor(selectedResource.status)">
            {{ getStatusText(selectedResource.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="容量">
          {{ selectedResource.capacity }}
        </DescriptionsItem>
        <DescriptionsItem label="价格">
          ¥{{ selectedResource.price }}
        </DescriptionsItem>
        <DescriptionsItem label="位置" :span="2">
          {{ selectedResource.location }}
        </DescriptionsItem>
        <DescriptionsItem label="描述" :span="2">
          {{ selectedResource.description }}
        </DescriptionsItem>
        <DescriptionsItem label="创建时间">
          {{ selectedResource.createTime }}
        </DescriptionsItem>
        <DescriptionsItem label="更新时间">
          {{ selectedResource.updateTime }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>
  </div>
</template>

<style scoped>
.business-resource-catalog {
  padding: 20px;
}

.catalog-header {
  padding: 20px;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.catalog-content {
  margin-bottom: 24px;
}
</style>
